//
//  YTRealmManager.m
//  YiTuUserClient
//
//  Created by 石少庸 on 2017/3/23.
//  Copyright © 2017年 YiTu. All rights reserved.
//

#import "YTRealmManager.h"
#import <Realm/Realm.h>
@implementation YTRealmManager

+ (RLMRealm *)defaultRealm {
    NSString *filePath = [self creatPathWithDataBaseName:@"default"];
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    config.fileURL = [[NSURL URLWithString:filePath] URLByAppendingPathExtension:@"realm"];
    config.readOnly = NO;
    // 这个设置会自动设置到defaultRealm里面去
    [RLMRealmConfiguration setDefaultConfiguration:config];
    return [RLMRealm defaultRealm];
}

+ (RLMRealm *)openDataBaseWithName:(NSString *)dataBaseName {
    NSString *filePath = [self creatPathWithDataBaseName:dataBaseName];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    config.fileURL = [[NSURL URLWithString:filePath] URLByAppendingPathExtension:@"realm"];
    config.readOnly = NO;
    // 通过配置打开 Realm 数据库
    RLMRealm *realm = [RLMRealm realmWithConfiguration:config error:nil];
    return realm;
}

+ (void)removeAllRealmDataBase:(void (^)())completion {
    [[self defaultRealm] beginWriteTransaction];
    [[self defaultRealm] deleteAllObjects];
    [[self defaultRealm] commitWriteTransaction];
    
    [self removeDataWithName:@"inlandCity"];
    [self removeDataWithName:@"foreignCity"];
    [self removeDataWithName:@"hotCity"];
    [self removeDataWithName:@"inlandAirportHot"];
    [self removeDataWithName:@"foreignAirportHot"];
    [self removeDataWithName:@"inlandAirport"];
    [self removeDataWithName:@"foreignAirport"];
    if (completion) {
        completion();
    }
}

+ (void)removeDataWithName:(NSString *)name {
    [[self openDataBaseWithName:name] beginWriteTransaction];
    [[self openDataBaseWithName:name] deleteAllObjects];
    [[self openDataBaseWithName:name] commitWriteTransaction];
}

#pragma mark - Pivate


/**
 这个方法会根据传入的数据库名称来创建一个数据库
 同时，会根据这个数据库的名称存储一个

 @param dataBaseName 数据库名称
 @return 返回存储路径
 */
+ (NSString *)creatPathWithDataBaseName:(NSString *)dataBaseName {
    NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [docPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:dataBaseName];
    NSLog(@"%@", filePath);
    return filePath;
}

@end
